<template>
  <div>
    <div class='home-title-bg' v-if='insq' v-show="titleBg"></div>
    <div v-if="hasdata==0"></div>
    <div v-else-if="hasdata==1" :class="{'fix-scroll':insq}">
      <div class='home-cont'>
        <!-- <newPeople v-if="localUserInfos&&!insq"></newPeople> -->
        <!-- <wxThirdRgest v-if="!insq"></wxThirdRgest> -->
        <div class="flex-center nav-search" v-if="!insq" @click="goSearch()">
          <!-- :style="insq?'top:80px;':''" -->
          <img :src="sImg" alt="">
        </div>
        <!-- <div v-if="beeInfos&&isAnnicate&&$root.ISOpenBee">
            <p class="annunciate" :class="{'isShowBee':isShowBee}" :style="{top:'-'+beeInfoHeight+'px'}">
              <img :src="beeInfos.img" alt="">
              <span class="arrow_down">
                <img src='//files.eyee.com/mcdn/static/img/bee_upbtn.png' alt="" v-if="!isShowBee" @click="showAnnica(1)">
                <span class="bee_close" v-if="isShowBee"  @click="showAnnica(0)"></span>
              </span>
            </p>
          </div> -->
        <!-- <mt-loadmore :top-distance="50" :top-method="reload" :bottom-all-loaded="true" ref="load"> -->
        <div>
          <div :style='{height:flashHeight}'>
            <home-flash :flash="flash" :qzone='insq'></home-flash>
          </div>

          <hot-brand class="gap" :brands="rcdbrand" :qzone='insq'></hot-brand>
          <div class="home_coupon" v-if="couponender && couponender.isexistscoupon">
            <img :src="couponender.banner|https" alt="" @click="goCouponList()">
          </div>

          <template v-if="!insq">
            <hot-news class="gap"></hot-news>
            <cutenter></cutenter>
            <grouppon></grouppon>
            
            <limit-swiper class="gap"></limit-swiper>
            <v-delay :delay="500">
              <HomeSupreme :supremes="specialBrand"></HomeSupreme>
            </v-delay>
            <!-- <v-delay :delay="500">
              <ul v-if="snakerInfos" class="gap home_sneaker_imgs clearfix">
                <li v-for="(sneak, index) in snakerInfos" :key="index">
                  <img :src="sneak.img|https" alt="" @click="goSex(index)">
                </li>
              </ul>
            </v-delay> -->
            <v-delay :delay="500">
              <FashionShop class="gap" :fashionShops="fashionshops"></FashionShop>
            </v-delay>
            <v-delay :delay="1000">
              <hot-product class="gap" :products="products"></hot-product>
            </v-delay>
            <v-delay :delay="1500">
              <!-- <shop-street class="gap" :shops="shopstreet"></shop-street> -->
              <!--热门分类-->
              <hot-category class="gap" :categorys="rcdcategory"></hot-category>
              <!-- <div style="text-align:left;" v-if="subjects&&subjects.length>0">
                <div class="sec-title" style="margin-bottom:15px;">
                  <p class="ico-btline">活动推荐11<br>
                    <span>RECOMMENDED ACTIVITIES</span>
                  </p>
                </div>
                <div class='home-acts' v-for="(item,idx) in subjects" :key="item.id" @click='activityGo(item,idx)'>
                  <img :src="item.picurl|https" alt="">
                </div> -->
                <!-- <template v-for="(item,index) in subjects">
                  <router-link v-if="(/\/active\/[a-zA-Z0-9]{32,36}/.test(item.link))" :to="'/active/'+item.id" :key="index">
                    <img :src="item.picurl|https" alt="">
                  </router-link>
                  <a v-else :href="item.link" :key="index">
                    <img :src="item.picurl|https" alt="">
                  </a>
                </template> -->
              <!-- </div> -->
            </v-delay>
            <div class="gess-like">
              <p class="title">- 猜你喜欢 -</p>
               <v-cutlist :more-handle='loadmore' :more-handling='css.isLoading' :isend='css.isEnd' v-if="css.hasData">
                 <div class="content flex-between flex-wrap">
                    <div class="like-product " v-for="(item,ind) in likeList" :key="ind" @click.stop="gotoDetail(item.id,item.requestid)">
                        <div class="prooduct-img">
                          <img :src="item.mainpic" alt="">
                        </div>
                        <div class="price">
                          <span class="specialprice" >￥{{(item.specialprice>0&&item.specialprice?item.specialprice:item.saleprice)|tofixed}}</span>
                          <span class="saleprice" v-if="item.specialprice>0">￥{{item.saleprice|tofixed}}</span>
                        </div>
                        <div class="brand-name ellipsis">{{item.brandname}}</div>
                        <div class="product-name ellipsis">{{item.name}}</div>
                    </div>
                  </div>
                   <div class='no-more' v-show="!css.hasData">已经到底啦~~</div>
               </v-cutlist>
            </div>
          </template>
          <div v-else>
            <v-delay :delay="400">
              <limit-swiper class="gap" :qzone='insq'></limit-swiper>
              <hot-category class="gap" :categorys="rcdcategory" :qzone='insq'></hot-category>
            </v-delay>
            <v-delay :delay="600">
              <div class="sec-title">
                <p class="ico-btline">潮品推荐<br>
                  <span>ITEM RECOMMENDED</span>
                </p>
              </div>
              <div class='flex-wrap home-rcds'>
                <div class='home-rcd' v-for="(item,idx) in products" :key='item.id' @click="goProduct(item,idx)">
                  <product-unit :product-item="item" :product-type='5' :qzone='insq'></product-unit>
                </div>
              </div>
            </v-delay>
          </div>
          <!-- <v-delay :delay="800">
            <div class='no-more' v-show="nomore">已经到底啦~~</div>
          </v-delay> -->
          <!-- </mt-loadmore> -->
        </div>
      </div>
      <div class="layer-enter" v-if="layerEnter.isshow" @click="enterGo">
        <img :src="layerEnter.icon" alt="">
      </div>
    </div>
    <v-error v-else></v-error>
  </div>
</template>
<script>
import { ENUM, DateBetween } from "../common/util";
// import { NewBaseHome } from '../common/api/base'
// import { ShoeGetTabs } from '../common/api/sneaker'
import { mapGetters } from "vuex";
import HomeFlash from "./templates/HomeFlash";
import HotBrand from "./templates/HotBrand";

import FashionShop from "./templates/FashionShop";
import HotCategory from "./templates/HotCategory";
import HotProductSwiper from "./templates/HotProductSwiper";
import LimitSwiper from "./templates/LimitSwiper";
import HotNews from "./templates/HotNews";
import Grouppon from "./group/GroupPromotionOnHomePage";
import cutenter from "./helpbargain/cutenterpage";
import HomeSupreme from "./templates/HomeSupreme.vue";
// import HomeShopStreet from './templates/HomeShopStreet'
// import NewHomeShopStreet from './templates/NewHomeShopStreet'
// 使用新的店铺街模板需要吧main版本换2.2.5
// import newPeople from "./templates/newPeople.vue";
import ProductUnit from "./templates/ProductUnit";
import wxThirdRgest from "./templates/wxThirdRgest";
import { guessWhatYouLike } from "../common/api/product";
const doc = window.document;

const TargetTab = [] // ["", "/news", "/sneaker", "/mall", "/user/home"];
const wss = window.sessionStorage;
const TabSSKEY = "MEMBER_FIRST_TAB";

export default {
  components: {
    HomeFlash,
    HotNews,
    Grouppon,
    cutenter,
    HotBrand,
    HotCategory,
    LimitSwiper,
    "hot-product": HotProductSwiper,
    // 'shop-street': NewHomeShopStreet,
    FashionShop,
    HomeSupreme,
    // newPeople,
    ProductUnit,
    wxThirdRgest
  },
  data() {
    return {
      // insq: window.INSQ,
      css: {
        isLoading: false,
        isEnd: false,
        hasData: true
      },
      pagination: {
        pageindex: 1,
        hasLoad: true
      },
      likeList: [],
      hasdata: 0,
      flashHeight: window.innerWidth * 0.8 + "px",
      nomore: false,
      sImg: "//files.eyee.com/static/img/search_white.png", // require('../assets/img/search_white.png')
      // arrowImg: require('../assets/img/bee_upbtn.png'),
      isShowBee: false,
      beeInfos: {},
      isAnnicate: false,
      snakerInfos: [],
      homeLayerEnter: {},
      beeInfoHeight: 0,
      isbindHobby: false,
      addpanduan: true,
      titleBg: false
    };
  },
  computed: {
    ...mapGetters({
      insq: "insq",
      flash: "homeFlash",
      couponender: "homeCouponEnter",
      specialBrand: "homeSpecialBrands",
      fashionshops: "homeFashionShop",
      products: "productRecommends",
      subjects: "homeSubjects",
      rcdbrand: "brandRecommeds",
      rcdcategory: "categoryRecommeds",
      user: "userInfo",
      shopstreet: "homeShopStreet" //sneakBrand: 'sneakBrandCate',
    }),
    // searchUrl() {
    //   return '/search/' + ENUM.SearchType.product.val
    // },
    getBaseValue() {
      // console.log(this.$store.getters.baseValue)
      return this.$store.getters.baseValue;
    },
    layerEnter() {
      let { activityurl, icon, isshow } = this.homeLayerEnter || {};
      let isIn = false;
      isshow = isshow && !!activityurl;
      if (isshow) {
        isIn =
          activityurl.indexOf("m.eyee.com") > -1 &&
          activityurl.indexOf("m.eyee.com/a/") < 0;
        if (isIn)
          activityurl = activityurl.replace(/^https?:\/\/.*?\.com/i, "");
      }
      return { isshow, isIn, activityurl, icon };
    },
    // ,
    // localUserInfos() {

    //   this.addpanduan = this.insq || this.user.token || sessionStorage.getItem('flg') ? false : true
    //   if (sessionStorage.getItem('newpeople') && this.user.token) {
    //     this.addpanduan = true
    //   }
    //   return this.addpanduan
    // }
  },
  beforeMount() {
    // console.log('home beforeMount',this.getBaseValue)
    // 可配置的首次进入 切换tab 处理
    let tabed = wss.getItem(TabSSKEY);
    if (!tabed) {
      wss.setItem(TabSSKEY, "1");
      let { targettabindex } = (this.getBaseValue || {}).configs || {};
      if (!isNaN(targettabindex)) {
        let redirectPath = TargetTab[targettabindex];
        redirectPath && this.$router.replace(redirectPath);
      }
    }
  },
  mounted() {
    let _ = this;

    _.mtaReport("0_shouye_bg");

    // 2018-10-24 移到watch里
    // let gbv = _.getBaseValue
    // if (gbv && gbv.configs) {
    //   let { annunciate, sneakerentrance, homefloatingactivityinfo } = gbv.configs
    //   if (annunciate && !_.insq) {
    //     _.beeInfos = JSON.parse(annunciate)
    //     _.isAnnicate = DateBetween({ begin: _.beeInfos.begintime, end: _.beeInfos.endtime })
    //   }
    //   if (sneakerentrance) _.snakerInfos = JSON.parse(sneakerentrance)

    //   if(homefloatingactivityinfo) _.homeLayerEnter = JSON.parse(homefloatingactivityinfo)
    // }
    if (_.getBaseValue) _.getFromBase(_.getBaseValue);

    // console.log(_.sneakBrand)
    // if (_.sneakBrand && !this.sneakBrand.share) {_.sneakInfo()};
    let deviceWid = doc.documentElement
      ? doc.documentElement.clientWidth
      : doc.body.clientWidth;
    _.beeInfoHeight = (((1.28 * deviceWid) / 6) * 5).toFixed(1);
    //    console.log(_.beeInfoHeight)
    //     _.initShare({ info: { title: '这是个斗牛H5首页的分享', desc: '分享的内容' }});
    _.initShare();

    if (
      (_.flash && _.flash.length > 0) ||
      (_.rcdbrand && _.rcdbrand.length > 0)
    ) {
    } else _.$store.dispatch("setHomeGather");
    _.hasdata = 1;

    const doQzone = () => {
      window.chaowuapi.setNavbar("white");
      window.chaowuapi.dispatchEvent("loadedIframe");
      window.chaowuapi.addEventListener("switchTab", function(data) {
        if (data.page === "home")
          window.chaowuapi.setNavbar(_.titleBg ? "black" : "white");
      });
    };

    _.$nextTick(() => {
      // console.log('home nextTick')
      doc.querySelector("body").classList.remove("waiting-home");

      if (window.chaowuapi) doQzone();
      else {
        setTimeout(() => {
          if (window.chaowuapi) doQzone();
        }, 600);
      }

      _.nomore = true;
      if (_.insq)
        doc
          .querySelector(".fix-scroll")
          .addEventListener("scroll", this.moveScroll);
    });

    //猜你喜欢
    this.like();
  },
  beforeDestroy() {
    if (this.insq) {
      let ele = doc.querySelector(".fix-scroll");
      ele && ele.removeEventListener("scroll", this.moveScroll);
    }
  },
  methods: {
    loadmore() {
      if (this.css.isEnd === true) {
        this.toast("已无更多");
      } else {
        this.pagination.pageindex += 1;
        this.like();
      }
    },
    like() {
      if (this.css.isLoading) return;
      this.css.isLoading = true;
      // this.isEnd = true;
      let postParams = {
        pageindex: this.pagination.pageindex
        // size: this.pagination.pagesize,
      };
      if (postParams.pageindex === 1) {
        this.css.isEnd = false;

        window.scrollTo(0, 0);
      }
      if (postParams.pageindex >= 10) {
        return;
      }

      guessWhatYouLike(postParams, this.pagination.hasLoad)
        .then(res => {
          if (res && res.list.length > 0) {
            this.likeList.push(...res.list);
            console.log("猜你喜欢数据: ", this.likeList);
            this.css.hasData = true;
          } else {
            this.css.isEnd = true;
            if (this.likeList.length == 0) {
              this.css.hasData = false;
            }
          }
          if (res.pageindex * res.pagesize >= res.sumcount) {
            this.css.isEnd = true;
          }
          this.css.isLoading = false;
        })
        .catch(e => {
          console.error(e);
          this.css.isLoading = false;
          this.css.hasData = false;
        });
    },
    gotoDetail(id, requestid) {
      let re = requestid ? requestid : "1542250997251444";
      this.$router.push({
        path: "/productDetail/" + id,
        query: { requestid: re }
      });
    },
    getFromBase(val) {
      let _ = this;
      if (val && val.configs) {
        let {
          annunciate,
          sneakerentrance,
          homefloatingactivityinfo
        } = val.configs;
        if (annunciate && !_.insq) {
          _.beeInfos = JSON.parse(annunciate);
          _.isAnnicate = DateBetween({
            begin: _.beeInfos.begintime,
            end: _.beeInfos.endtime
          });
        }
        if (sneakerentrance) _.snakerInfos = JSON.parse(sneakerentrance);

        if (homefloatingactivityinfo)
          _.homeLayerEnter = JSON.parse(homefloatingactivityinfo);
      }
    },
    enterGo() {
      let _ = this,
        { isIn, activityurl } = _.layerEnter;
      if (isIn) _.$router.push(activityurl);
      else window.location.href = activityurl;
    },
    moveScroll(e) {
      // let cont = doc.querySelector('.fix-scroll')
      // let rect = cont.getBoundingClientRect()
      // // console.log('home moveScroll', cont.scrollTop, rect)
      // if (cont.scrollTop < rect.width - 160) this.titleBg = false
      // else this.titleBg = true
      let ele = e.target;
      // console.log(ele.scrollTop, ele.clientWidth)
      if (ele.scrollTop < ele.clientWidth - 160) {
        if (this.titleBg) {
          this.titleBg = false;
          window.chaowuapi.setNavbar("white");
        }
      } else {
        if (!this.titleBg) {
          this.titleBg = true;
          window.chaowuapi.setNavbar("black");
        }
      }
    },
    // req() {
    //   NewBaseHome().then(res => {
    //     this.hasdata = 1;
    //     this.$store.dispatch('setHomeGather', res);
    //   }).catch(e => { this.hasdata = 2; this.toast(e && e.msg ? e.msg : ('error:' + e)); });
    // },
    reload() {
      //      this.req();
      this.$refs.load.onTopLoaded();
      // this.$store.dispatch('changLimit', true);
    },
    showAnnica(idx) {
      console.log(idx);
      if (idx == 1) {
        this.isShowBee = idx === 1 ? true : false;
      } else {
        this.$root.ISOpenBee = false;
      }
    },
    goSex(n) {
      // this.$router.push('/sneakerSex/' + n + '/' + this.sneakBrand.tabs[n].brands[0].brandid)
      let rect = doc
        .querySelector(".home_sneaker_imgs")
        .getBoundingClientRect();
      this.report("首页-sneaker入口", n ? "女鞋" : "男鞋", {
        bottom: rect.bottom,
        height: rect.height,
        top: rect.top,
        width: rect.width,
        x: rect.x,
        y: rect.y
      });
      this.$router.push("/sneaker?type=" + n);
    },
    // sneakInfo() {
    //   ShoeGetTabs().then((res) => {
    //     if (res) {
    //       console.log('ShoeGetTabs', res);
    //       this.$store.dispatch('setSneakBrandCate', res)
    //     }
    //   }).catch(e => {
    //     console.error('数据加载失败', e); })
    // },
    goCouponList() {
      let rect = doc.querySelector(".home_coupon").getBoundingClientRect();
      this.report("首页-优惠券入口", "", {
        bottom: rect.bottom,
        height: rect.height,
        top: rect.top,
        width: rect.width,
        x: rect.x,
        y: rect.y
      });
      // this.$router.push('/coupon')
      this.insq ? this.qzoneGo("/coupon") : this.$router.push("/coupon");
    },
    goSearch() {
      this.report("首页-悬浮搜索");
      this.mtaReport("0_sousuo_dj");

      let url = "/search/" + ENUM.SearchType.product.val;
      this.insq ? this.qzoneGo(url) : this.$router.push(url);
    },
    menuGo(item) {
      let rect = doc.querySelector(".home-menu").getBoundingClientRect();
      this.report("首页-菜单入口", item.name, {
        bottom: rect.bottom,
        height: rect.height,
        top: rect.top,
        width: rect.width,
        x: rect.x,
        y: rect.y
      });
      this.qzoneGo(item.link);
    },
    goProduct(item, idx) {
      let rect = window.document
        .getElementsByClassName("home-rcd")
        [idx].getBoundingClientRect();
      this.report("首页-推荐商品", `平铺第${idx + 1}个`, {
        id: item.id,
        name: item.name,
        bottom: rect.bottom,
        height: rect.height,
        top: rect.top,
        width: rect.width,
        x: rect.x,
        y: rect.y
      });
    },
    activityGo(item, idx) {
      let rect = window.document
        .getElementsByClassName("home-acts")
        [idx].getBoundingClientRect();
      this.report("首页-活动推荐", `第${idx + 1}个`, {
        id: item.id,
        bottom: rect.bottom,
        height: rect.height,
        top: rect.top,
        width: rect.width,
        x: rect.x,
        y: rect.y
      });

      this.$router.push("/active/" + item.id);
    }
  },
  watch: {
    // flash() {
    //   if (this.flash && this.flash.length > 0) {
    //     this.hasdata = 1
    //   }
    // },
    getBaseValue: function(val, oldVal) {
      // console.log('watcher getBaseValue', val)
      this.getFromBase(val);

      // if (curVal && curVal.configs.annunciate) {
      //   console.log(JSON.parse(curVal.configs.annunciate))
      //   this.beeInfos = JSON.parse(curVal.configs.annunciate)
      //   this.isAnnicate = DateBetween({ begin: this.beeInfos.begintime, end: this.beeInfos.endtime })
      // }
      // if (curVal && curVal.configs.sneakerentrance) {
      //   this.snakerInfos = JSON.parse(curVal.configs.sneakerentrance)
      //   console.log(JSON.parse(curVal.configs.sneakerentrance))
      // }
    }
  }
};
</script>
<style scoped>
.gess-like {
  text-align: center;
}
.gess-like .title {
  font-weight: bold;
}
.gess-like .content {
  padding: 2%;
  padding-top: 30px;
}
.like-product {
  width: 49%;
  font-size: 12px;
  text-align: left;
  margin-bottom: 20px;
}
.like-product .prooduct-img {
  width: 100%;
  height: 0;
  /* padding-top: 100%; */
  padding-bottom: 100%;
}
/* .like-product .prooduct-img img {
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
} */
.like-product .price {
  font-size: 12px;
  color: #999;
}
.like-product .price .specialprice {
  font-size: 16px;
  color: #333;
  font-weight: bold;
}
.like-product .price .saleprice {
  text-decoration: line-through;
}
.like-product .brand-name {
  color: #333;
  width: 100%;
  font-weight: bold;
}
.like-product .product-name {
  color: #999;
  width: 100%;
}
</style>

